package topofstack.networkserverutils.net;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Whois {
	public static String get(String url, boolean isIP) {
		String result;
		if(!isIP)
			result = performWhoisQuery("whois.internic.net", 43, "=" + url, false);
		else
			result = performWhoisQuery("whois.arin.net", 43, url, true);
		
		return result;
	}
	
	public static String performWhoisQuery(String host, int port, String query, boolean isIP) {

		String result = "";

		try {
			Socket socket = new Socket(host, port);

			InputStreamReader isr = new InputStreamReader(
					socket.getInputStream());
			BufferedReader in = new BufferedReader(isr);

			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			out.println(query);

			String line = "";
			
			if(isIP) {
				while((line = in.readLine()) != null) {
					if(!line.startsWith("#")) {
						String contents[] = line.trim().split("[:]");
						if(contents.length == 2)
							result += String.format("%-10s: %s\n", 
									contents[0].trim(), contents[1].trim());
						else
							result += line + "\n"; 
					}
				}
			}
			else {
				boolean flag = false;
				while ((line = in.readLine()) != null) {
					if (line.contains("Server Name:")
							|| line.contains("Domain Name:"))
						flag = true;
					else if (line.contains(">>>"))
						break;
					if (flag) {
						if (line.trim().length() == 0) {
							result += "\n";
						}						
						else{
							String contents[] = line.trim().split(":");
							String type = contents[0].trim();
							if (type.contains("Domain Name") || type.contains("Server Name")) {
								result += type + " : ";
								String urlParts[] = contents[1].toLowerCase()
										.trim().split("[.]");
								for (String urlPart : urlParts) {
									result += urlPart;
									if (urlPart.contains("com") || urlPart.contains("net")
											|| urlPart.contains("org")) 
										break;
									result += ".";
								}
								result += "\n";
								
							} else if (type.equals("IP Address")
									|| type.equals("Registrar")
									|| type.equals("Name Server")) {
								result += line.trim() + "\n";
							}
						}
	
					}
				}
			}
		} 
		catch (Exception exception) {
			return null;
		}

		return result;
	}
	
	
}
